"""
银行业务接口
"""

from db import db_handler


def withdraw_interface(username: str, sum: int) -> tuple:
    """提现接口"""
    user_dict = db_handler.select(username)
    balance = user_dict.get('balance')

    # 添加手续费（5%）
    total_sum = sum * 1.05

    # 判断余额是否足够提现
    if balance >= total_sum:
        # 从余额减去提现金额并更新到字典
        user_dict['balance'] = balance
        balance -= total_sum

        # 保存提现后的新数据
        db_handler.save(username, user_dict)

        # 保存流水
        flow = f'提现{total_sum}元，手续费为{total_sum-sum}元'
        user_dict['flow'].append(flow)

        return True, f'成功提现{sum}元，手续费为{total_sum-sum}元'
    else:
        return False, '余额不足！'


def repay_interface(username: str, sum: int) -> tuple:
    """还款接口"""
    user_dict = db_handler.select(username)
    user_dict['balance'] += sum
    db_handler.save(username, user_dict)

    # 保存流水
    flow = f'还款{sum}元'
    user_dict['flow'].append(flow)

    return True, f'成功还款{sum}元！'


def transfer_interface(username: str, target_user: str, sum: int) -> tuple:
    """转账接口"""

    # 获取用户信息
    user_dict = db_handler.select(username)
    # 判断余额是否足够转账
    if user_dict.get('balance') < sum:
        return False, '您的余额不足！'

    # 获取转账目标用户信息
    target_user_dict = db_handler.select(target_user)
    if not target_user_dict:
        return False, f'目标用户{target_user}不存在！'

    # 转账
    user_dict['balance'] -= sum
    target_user_dict['balance'] += sum

    # 保存用户双方的数据
    db_handler.save(username)
    db_handler.save(target_user)

    # 保存当前用户流水
    flow = f'转账给{target_user} {sum}元'
    user_dict['flow'].append(flow)
    # 保存当前目标流水
    flow = f'来自{username}的转账{sum}元'
    target_user_dict['flow'].append(flow)

    return True, f'成功给{target_user}转账{sum}元！'


def check_flow_interface(username: str) -> list:
    """查看流水接口"""
    user_dict = db_handler.select(username)
    flow_list = user_dict.get('flow')
    return flow_list


def pay_interface(username: str, sum: int) -> tuple:
    """支付接口"""
    user_dict = db_handler.select(username)

    if user_dict.get('balance') < sum:
        return False, '余额不足！'
    else:
        user_dict['balance'] -= sum
        user_dict['flow'].append(f'购物消费：{sum}元')
        db_handler.save(username, user_dict)
        return True, '支付完成！'
